const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const app = express();
const port = 3000;

// 中间件
app.use(cors());
app.use(express.json());

// MySQL 连接配置
const connection = mysql.createConnection({
  host: '127.0.0.1',
  user: 'root',
  password: '88888888', // 请修改为你的 MySQL 密码
  database: 'chromenodebook', // 请修改为你的数据库名
  charset: 'utf8mb4'
});

// 连接数据库
connection.connect((err) => {
  if (err) {
    console.error('数据库连接失败:', err);
    return;
  }
  console.log('成功连接到 MySQL 数据库');
});

// API 路由：保存笔记
app.post('/api/notes', (req, res) => {
  const { title, type, keywords, source, content, thoughts, action } = req.body;
  
  // 如果是启动服务请求
  if (action === 'start_server') {
    const { startBackendServer } = require('./server-launcher');
    
    startBackendServer()
      .then(result => {
        res.json({ 
          success: true, 
          message: '服务启动命令已执行',
          result: result 
        });
      })
      .catch(error => {
        res.status(500).json({ 
          success: false, 
          message: '启动服务失败: ' + error.message 
        });
      });
    return;
  }
  
  // 正常的保存笔记请求
  const query = `
    INSERT INTO node_book (title, type, key_list, source, content, think) 
    VALUES (?, ?, ?, ?, ?, ?)
  `;
  
  connection.query(query, [title, type, keywords, source, content, thoughts], (err, results) => {
    if (err) {
      console.error('保存笔记失败:', err);
      res.status(500).json({ 
        success: false, 
        message: '保存失败: ' + err.message 
      });
      return;
    }
    
    console.log('笔记保存成功，ID:', results.insertId);
    res.json({ 
      success: true, 
      message: '笔记保存成功',
      id: results.insertId 
    });
  });
});

// API 路由：启动服务
app.get('/api/start', (req, res) => {
  console.log('收到服务启动请求');
  
  // 检查服务是否已经在运行
  if (connection.state === 'authenticated') {
    res.json({ 
      success: true, 
      message: '服务已经在运行',
      status: 'running'
    });
    return;
  }
  
  // 尝试重新连接数据库
  connection.connect((err) => {
    if (err) {
      console.error('数据库连接失败:', err);
      res.status(500).json({ 
        success: false, 
        message: '数据库连接失败: ' + err.message 
      });
      return;
    }
    
    console.log('数据库连接成功');
    res.json({ 
      success: true, 
      message: '服务启动成功',
      status: 'started'
    });
  });
});

// API 路由：获取笔记总数（多条件查询）
app.get('/api/notes/count', (req, res) => {
  // 查询条件
  const { title, type, source, content, think } = req.query;
  let where = [];
  let params = [];
  if (title) {
    where.push("title LIKE ?");
    params.push(`%${title}%`);
  }
  if (type) {
    where.push("type LIKE ?");
    params.push(`%${type}%`);
  }
  if (source) {
    where.push("source LIKE ?");
    params.push(`%${source}%`);
  }
  if (content) {
    where.push("content LIKE ?");
    params.push(`%${content}%`);
  }
  if (think) {
    where.push("think LIKE ?");
    params.push(`%${think}%`);
  }
  let whereSql = where.length ? ("WHERE " + where.join(" AND ")) : "";
  const query = `SELECT count(*) as total FROM node_book ${whereSql}`;
  connection.query(query, params, (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    res.json({ success: true, total: results[0].total });
  });
});

// API 路由：获取所有笔记（分页+多条件查询）
app.get('/api/notes', (req, res) => {
  let page = parseInt(req.query.page) || 1;
  let pageSize = parseInt(req.query.pageSize) || 10;
  if (page < 1) page = 1;
  if (pageSize < 1) pageSize = 10;
  const offset = (page - 1) * pageSize;

  // 查询条件
  const { title, type, source, content, think } = req.query;
  let where = [];
  let params = [];
  if (title) {
    where.push("title LIKE ?");
    params.push(`%${title}%`);
  }
  if (type) {
    where.push("type LIKE ?");
    params.push(`%${type}%`);
  }
  if (source) {
    where.push("source LIKE ?");
    params.push(`%${source}%`);
  }
  if (content) {
    where.push("content LIKE ?");
    params.push(`%${content}%`);
  }
  if (think) {
    where.push("think LIKE ?");
    params.push(`%${think}%`);
  }
  let whereSql = where.length ? ("WHERE " + where.join(" AND ")) : "";

  const query = `SELECT id as '主键', title as '标题', type as '类型', key_list as '关键词', source as '来源', create_time as '创建时间' FROM node_book ${whereSql} ORDER BY id DESC LIMIT ?, ?`;
  params.push(offset, pageSize);
  connection.query(query, params, (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    // 修正 create_time 字段为本地时间字符串
    const formatDate = (dt) => {
      if (!dt) return '';
      const date = new Date(dt);
      const pad = n => n < 10 ? '0' + n : n;
      return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    };
    const data = results.map(row => {
      if (row['创建时间']) {
        row['创建时间'] = formatDate(row['创建时间']);
      }
      return row;
    });
    res.json({ success: true, data });
  });
});

// API 路由：获取随机笔记（用于复习）
app.get('/api/notes/random', (req, res) => {
  const query = `
    SELECT 
      id as '主键',
      title as '标题',
      type as '类型',
      key_list as '关键词',
      content as '内容',
      think as '思考',
      source as '来源',
      create_time as '创建时间',
      review_count as '复习次数'
    FROM node_book 
    WHERE review_count = (SELECT MIN(review_count) FROM node_book) 
    ORDER BY RAND() 
    LIMIT 1
  `;
  
  connection.query(query, (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    
    if (results.length === 0) {
      res.json({ success: true, data: null, message: '暂无笔记' });
      return;
    }
    
    // 修正 create_time 字段为本地时间字符串
    const formatDate = (dt) => {
      if (!dt) return '';
      const date = new Date(dt);
      const pad = n => n < 10 ? '0' + n : n;
      return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    };
    
    const note = results[0];
    if (note['创建时间']) {
      note['创建时间'] = formatDate(note['创建时间']);
    }
    
    res.json({ success: true, data: note });
  });
});

// API 路由：标记笔记为已复习
app.post('/api/notes/:id/review', (req, res) => {
  const id = req.params.id;
  const query = "UPDATE node_book SET review_count = review_count + 1 WHERE id = ?";
  connection.query(query, [id], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    if (results.affectedRows === 0) {
      res.status(404).json({ success: false, message: '未找到该笔记' });
      return;
    }
    res.json({ success: true, message: '复习次数已更新' });
  });
});

// API 路由：获取笔记详情
app.get('/api/notes/:id/detail', (req, res) => {
  const id = req.params.id;
  const query = `
    SELECT 
      id as '主键',
      title as '标题',
      type as '类型',
      key_list as '关键词',
      content as '内容',
      think as '思考',
      source as '来源',
      create_time as '创建时间',
      review_count as '复习次数'
    FROM node_book 
    WHERE id = ?
  `;
  connection.query(query, [id], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    if (results.length === 0) {
      res.status(404).json({ success: false, message: '未找到该笔记' });
      return;
    }
    
    // 修正 create_time 字段为本地时间字符串
    const formatDate = (dt) => {
      if (!dt) return '';
      const date = new Date(dt);
      const pad = n => n < 10 ? '0' + n : n;
      return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    };
    
    const note = results[0];
    if (note['创建时间']) {
      note['创建时间'] = formatDate(note['创建时间']);
    }
    
    res.json({ success: true, data: note });
  });
});

// API 路由：获取笔记编辑详情
app.get('/api/notes/:id/edit', (req, res) => {
  const id = req.params.id;
  const query = "SELECT id as '主键', title as '标题', type as '类型', key_list as '关键词', source as '来源', content as '内容', think as '思考' FROM node_book WHERE id = ?";
  connection.query(query, [id], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    if (results.length === 0) {
      res.status(404).json({ success: false, message: '未找到该笔记' });
      return;
    }
    res.json({ success: true, data: results[0] });
  });
});

// API 路由：更新笔记
app.put('/api/notes/:id/edit', (req, res) => {
  const id = req.params.id;
  const { title, type, key_list, source, content, think } = req.body;
  const query = "UPDATE node_book SET title=?, type=?, key_list=?, source=?, content=?, think=? WHERE id=?";
  connection.query(query, [title, type, key_list, source, content, think, id], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    res.json({ success: true, message: '更新成功' });
  });
});

// API 路由：获取置顶笔记总数
app.get('/api/notes/pinned/count', (req, res) => {
  const query = "SELECT count(*) as total FROM node_book WHERE is_pinned = 1";
  connection.query(query, (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    res.json({ success: true, total: results[0].total });
  });
});

// API 路由：获取置顶笔记列表（分页）
app.get('/api/notes/pinned', (req, res) => {
  let page = parseInt(req.query.page) || 1;
  let pageSize = parseInt(req.query.pageSize) || 3;
  if (page < 1) page = 1;
  if (pageSize < 1) pageSize = 3;
  const offset = (page - 1) * pageSize;

  const query = `
    SELECT 
      id AS '主键',
      title AS '标题',
      type AS '类型',
      key_list AS '关键词',
      content AS '内容',
      think AS '思考',
      source AS '来源',
      create_time AS '创建时间'
    FROM node_book 
    WHERE is_pinned = 1 
    ORDER BY pinned_time DESC
    LIMIT ?, ?
  `;
  
  connection.query(query, [offset, pageSize], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    // 修正 create_time 字段为本地时间字符串
    const formatDate = (dt) => {
      if (!dt) return '';
      const date = new Date(dt);
      const pad = n => n < 10 ? '0' + n : n;
      return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    };
    const data = results.map(row => {
      if (row['创建时间']) {
        row['创建时间'] = formatDate(row['创建时间']);
      }
      return row;
    });
    res.json({ success: true, data });
  });
});

// API 路由：置顶笔记
app.post('/api/notes/:id/pin', (req, res) => {
  const id = req.params.id;
  const query = "UPDATE node_book SET is_pinned = 1, pinned_time = NOW() WHERE id = ?";
  connection.query(query, [id], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    if (results.affectedRows === 0) {
      res.status(404).json({ success: false, message: '未找到该笔记' });
      return;
    }
    res.json({ success: true, message: '笔记已置顶' });
  });
});

// API 路由：取消置顶笔记
app.post('/api/notes/:id/unpin', (req, res) => {
  const id = req.params.id;
  const query = "UPDATE node_book SET is_pinned = 0, pinned_time = NULL WHERE id = ?";
  connection.query(query, [id], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    if (results.affectedRows === 0) {
      res.status(404).json({ success: false, message: '未找到该笔记' });
      return;
    }
    res.json({ success: true, message: '已取消置顶' });
  });
});

// API 路由：删除笔记
app.delete('/api/notes/:id/delete', (req, res) => {
  const id = req.params.id;
  const query = 'DELETE FROM node_book WHERE id = ?';
  connection.query(query, [id], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    res.json({ success: true, message: '删除成功' });
  });
});

// 新增API：保存AI问答历史
app.post('/api/ai_qa_history', (req, res) => {
  const { note_id, user_question, model_answer, model_used } = req.body;
  if (!note_id || !user_question || !model_used) {
    res.status(400).json({ success: false, message: '参数不完整' });
    return;
  }
  const query = `INSERT INTO ai_qa_history (note_id, user_question, model_answer, model_used) VALUES (?, ?, ?, ?)`;
  connection.query(query, [note_id, user_question, model_answer, model_used], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: '保存AI问答历史失败: ' + err.message });
      return;
    }
    res.json({ success: true, id: results.insertId });
  });
});

// 新增API：获取所有笔记类型
app.get('/api/note_types', (req, res) => {
  const query = 'SELECT value FROM note_type_enum';
  connection.query(query, (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    // 返回类型数组
    res.json({ success: true, data: results.map(row => row.value) });
  });
});

// 新增API：新增类型
app.post('/api/note_types', (req, res) => {
  const { value } = req.body;
  if (!value) {
    res.status(400).json({ success: false, message: '类型名称不能为空' });
    return;
  }
  const query = 'INSERT INTO note_type_enum (value) VALUES (?)';
  connection.query(query, [value], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    res.json({ success: true });
  });
});
// 新增API：删除类型
app.delete('/api/note_types/:value', (req, res) => {
  const value = req.params.value;
  if (!value) {
    res.status(400).json({ success: false, message: '类型名称不能为空' });
    return;
  }
  const query = 'DELETE FROM note_type_enum WHERE value = ?';
  connection.query(query, [value], (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: err.message });
      return;
    }
    res.json({ success: true });
  });
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在 http://127.0.0.1:${port}`);
});

// 优雅关闭
process.on('SIGINT', () => {
  connection.end();
  process.exit();
}); 